package com.uziot.bucket.rest.template.config;

import com.uziot.bucket.rest.template.util.StringPool;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author shidt
 * @version V1.0
 * @className RestTemplateInterceptor
 * @date 2020-08-19 19:54:25
 * @description RestTemplate请求拦截器，全局添加请求头以及请求信息
 */

@SuppressWarnings("NullableProblems")
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders httpHeaders = request.getHeaders();
        httpHeaders.set(StringPool.AUTHORIZATION, MDC.get(StringPool.AUTHORIZATION));
        httpHeaders.set(StringPool.TRACE_ID, MDC.get(StringPool.TRACE_ID));
        return execution.execute(request, body);
    }
}
